<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;

class GroupModel extends Model
{
	var $_level;

	function __construct()
	{
		parent::__construct('group');
	}

	function _addChildren(& $tree, $id = 0)
	{

		$this->setQuery('SELECT * FROM ##__group WHERE parent_id = '.intval($id));
		$groups = $this->db->loadAssocList();
		foreach ($groups as $group)
		{
			$group['level'] = $this->_level;
			$tree[] = $group;
			$this->_level += 1;
			$this->_addChildren($tree, $group['id']);
			$this->_level -= 1;
		}
	}


	function loadTree()
	{
		$tree = array();
		$this->_level = 0;
		$this->_addChildren($tree);
		return $tree;
	}

	function add($group_name, $parent = 0)
	{
		$this->setQuery('INSERT INTO ##__group (name,parent_id)'.
							' VALUES ('.$this->db->Quote($group_name).', '.intval($parent).')');

		$this->db->query();
		$group_id = $this->db->insertid();

		$this->db->setQuery('SELECT * FROM ##__roles');
		$roles = $this->db->loadAssocList();

		$default = array(
			'guest' => array (
				'read'			=> 1,
				'read_rss'		=> 1,
				'bbcode'		=> 0,
				'bbcode_img'	=> 0,
				'post_reply'	=> 0,
				'post_poll'		=> 0,
				'post_topic'	=> 0,
				'edit_topic'	=> 0,
				'edit_posts'	=> 0,
				'delete_topics'	=> 0,
				'delete_posts'	=> 0,
				'make_sticky'	=> 0,
				'close_topic'	=> 0,
				'use_captcha'	=> 0,
			),
			'member' => array (
				'read'			=> 1,
				'read_rss'		=> 1,
				'bbcode'		=> 1,
				'bbcode_img'	=> 1,
				'post_reply'	=> 1,
				'post_poll'		=> 1,
				'post_topic'	=> 1,
				'edit_topic'	=> 1,
				'edit_posts'	=> 1,
				'delete_topics'	=> 0,
				'delete_posts'	=> 0,
				'make_sticky'	=> 0,
				'close_topic'	=> 0,
				'use_captcha'	=> 0,
			),
			'moderator' => array (
				'read'			=> 1,
				'read_rss'		=> 1,
				'bbcode'		=> 1,
				'bbcode_img'	=> 1,
				'post_reply'	=> 1,
				'post_poll'		=> 1,
				'post_topic'	=> 1,
				'edit_topic'	=> 1,
				'edit_posts'	=> 1,
				'delete_topics'	=> 1,
				'delete_posts'	=> 1,
				'make_sticky'	=> 1,
				'close_topic'	=> 1,
				'use_captcha'	=> 0,
			),
			'admin' => array (
				'read'			=> 1,
				'read_rss'		=> 1,
				'bbcode'		=> 1,
				'bbcode_img'	=> 1,
				'post_reply'	=> 1,
				'post_poll'		=> 1,
				'post_topic'	=> 1,
				'edit_topic'	=> 1,
				'edit_posts'	=> 1,
				'delete_topics'	=> 1,
				'delete_posts'	=> 1,
				'make_sticky'	=> 1,
				'close_topic'	=> 1,
				'use_captcha'	=> 0,
			),
		);

		foreach ($roles as $role) {
			$role_name = strtolower(trim($role['name']));

			if (!isset($default[$role_name])) continue;
			$sql = 'INSERT INTO ##__permissions SET ';

			$fields = array();
			foreach ($default[$role_name] as $name=>$value) {
				$fields[] = $this->db->nameQuote($name).'='.$this->db->Quote($value);
			}
			$sql .= implode(', ',$fields);
			$this->db->setQuery($sql);
			$this->db->query();
			
			$access_id = $this->db->insertid();

			$role_id = intval($role['id']);

			$sql = 'INSERT INTO ##__group_permissions SET '.
								'group_id = '.$group_id.','.
								'role_id = '.$role_id.','.
								'access_id = '.$access_id;
			$this->db->setQuery($sql);
			$this->db->query();
		}
	}

	function _deleteChildren($id)
	{
		$id = intval($id);

		$this->setQuery('SELECT id FROM ##__group WHERE parent_id = '.$id);

		foreach ($this->db->loadResultArray() as $child_id)
		{
			$this->_deleteChildren($child_id);
		}

		$this->setQuery('DELETE FROM ##__group WHERE parent_id = '.$id);

		$this->db->query();

		$this->setQuery('DELETE FROM ##__user_group WHERE group_id='.$id);
		$this->db->query();

		$this->setQuery('DELETE FROM ##__group_forum WHERE group_id='.$id);
		$this->db->query();

		$this->setQuery('SELECT access_id FROM ##__group_permissions WHERE group_id='.$id);
		$ids = implode(',',$this->db->loadResultArray());

		if ($ids) {
			$this->setQuery('DELETE FROM ##__permissions WHERE id IN ('.$ids.')');
			$this->db->query();
		}

		$this->setQuery('SELECT access_id FROM ##__group_forum WHERE group_id='.$id);
		$ids = implode(',',$this->db->loadResultArray());

		if ($ids) {
			$this->setQuery('DELETE FROM ##__permissions WHERE id IN ('.$ids.')');
			$this->db->query();
		}

		$this->setQuery('DELETE FROM ##__group_permissions WHERE group_id='.$id);
		$this->db->query();
	}

	function delete($value)
	{
		parent::delete($value);
		$this->_deleteChildren($value);
	}

	//function getUserRole($group_id, $user_id)

	function loadUsers($group_id,$role_id)
	{
		$this->setQuery('SELECT users.* FROM ##__user_group as gr'.
							' INNER JOIN ##__users as users'.
							'  ON users.id = gr.user_id'.
							' WHERE gr.role_id = '.intval($role_id).
							' AND gr.group_id='.intval($group_id));
		return $this->db->loadAssocList();
	}

	function moveUser($group_id, $user_id, $target_role)
	{
		$this->setQuery('UPDATE ##__user_group SET role_id = '.intval($target_role).
							' WHERE user_id = '.intval($user_id).
							' AND group_id = '.intval($group_id));
		$this->db->query();
	}

	function load($value=NULL, $field='id')
	{
		$group = parent::load($value, $field);
		if (!$group) return false;

		if (!$group['parent_id']) return $group;

		$this->db->setQuery('SELECT name FROM '.$this->table.' WHERE id = '.$this->db->Quote($group['parent_id']));
		$group['parent_name'] = $this->db->loadResult();
		return $group;
	}

	function move($id,$new_parent)
	{
		if (!$new_parent) {
			$sql = 'UPDATE ##group SET parent_id = NULL WHERE id = '.intval($id);
		} else {
			$sql = 'UPDATE ##__group SET parent_id = '.$this->db->Quote($new_parent).' WHERE id = '.intval($id);
		}
		$this->db->setQuery($sql);

		if (!$this->db->query()) {
			print $this->db->getErrorMsg();die;
		}
	}

	function getAccess($id, $forum_id)
	{
		if (is_null($forum_id)) {
			$forum_sql = 'acl.forum_id IS NULL';
		} else {
			$forum_sql = 'acl.forum_id = \''.intval($forum_id) . '\'';
		}

		$sql = 'SELECT access.access,acl.id, access.id'.
				' FROM ##__access as access'.
				' INNER JOIN ##__acl as acl ON access.id = acl.access_id'.
				' WHERE acl.group_id = '.$this->db->Quote($id)." AND $forum_sql ORDER BY access.id";
		$this->db->setQuery($sql);

		if (!$this->db->query()) {
			print $this->db->getErrorMsg();die;
		}

		return $this->db->loadRowList();
	}

	function getParent($id)
	{
		$this->db->setQuery('SELECT parent_id FROM ##__group WHERE id = '.intval($id));
		return $this->db->loadResult();
	}

	function getChildren($id)
	{
		$this->db->setQuery('SELECT id FROM ##__group WHERE parent_id = '.intval($id));
		return $this->db->loadResultArray();
	}

	function deleteAccess($group_id, $access_id)
	{
		$this->setQuery('DELETE FROM ##__acl'.
				' WHERE group_id ='. intval($group_id).
				' AND access_id ='. intval($access_id));

		if (!$this->db->query()) {
			print $this->db->getErrorMsg();die;
		}
	}
	function addAccess($group_id, $access_id, $forum_id)
	{
		$group_id = intval($group_id);
		$access_id = intval($access_id);

		if (!is_null($forum_id))
		$forum_id = '\''.intval($forum_id).'\'';
		else
		$forum_id = 'NULL';

		$this->setQuery("INSERT INTO ##__acl".
				" (group_id, access_id, forum_id)".
				" VALUES ('$group_id','$access_id',$forum_id)");

		if (!$this->db->query()) {
			print $this->db->getErrorMsg();die;
		}
	}

	function addUser($group_id, $user_id, $role_id = 1, $lic_id = 0) { //joopport modified 
		$this->setQuery('SELECT id FROM ##__user_group WHERE user_id = '.intval($user_id).' AND group_id='.intval($group_id));
		$id = $this->db->loadResult();
		if (!is_null($id)) return;

		//$parent = $this->db->loadResult();

		$this->setQuery('INSERT INTO ##__user_group'.
					' (group_id,user_id,role_id,jooplicense_id)'.
					' VALUES ('.intval($group_id).', '.intval($user_id).', '.intval($role_id).', '.intval($lic_id).')');
		
		$this->db->query();
		
		// Iskar - We need to add the user to a group regardless of the groups' top hierarchy
		/*
		$this->setQuery('SELECT parent_id FROM ##__group WHERE id = '.intval($group_id));
		$parent = $this->db->loadResult();
		if ($parent != 0) {
			$this->addUser($parent,$user_id);
		}
		*/
	}

	function removeUser($group_id, $user_id)
	{
		$this->setQuery('DELETE FROM ##__user_group'.
								' WHERE group_id = '.$group_id.
								' AND user_id = '.$user_id);
		$this->db->query();
		$this->setQuery('SELECT group_id FROM ##__user_group AS ug'.
							' JOIN ##__group AS gr'.
							'  ON gr.id=ug.group_id'.
							' WHERE user_id='.intval($user_id).
							' AND parent_id='.intval($group_id));
		$children = $this->db->loadResultArray();

		foreach ($children as $child) {
			$this->removeUser($child, $user_id);
		}
	}
}
?>